package com.movie.playvideos.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.movie.playvideos.objects.MediaObject;

public class ConnectToServer {
	public interface GetTokenListener{
		public void getTokenSuccess (String data);
		public void getTokenFailure ();
	}
	public interface GetAuthenListener{
		public void getAuthenSuccess (String data);
		public void getAuthenFailure ();
	}
	public interface GetListVideoLiveListener{
		public void getVideoSuccess (MediaObject media);
		public void getVideoFailure ();
	}
	public interface GetStreammingUrl {
		public void getStreammingUrl (String url);
	}
	public static void removeCookies (Context mContext){
		PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
		myCookieStore.getCookies().clear();
	}
	public static void addHeader(final Context mContext, AsyncHttpClient client){
		PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
		client.setCookieStore(myCookieStore);
	}
	
	public static void getToken (final Context mContext, final GetTokenListener callback){
		removeCookies(mContext);
		AsyncHttpClient client = new AsyncHttpClient();
		Log.e("url get token", URL.urlGetToken());
		addHeader(mContext, client);
		client.get(mContext, URL.urlGetToken(), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String content) {
				// TODO Auto-generated method stub
				
				PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
				//Cookie cookie = 
				Log.e("cookies: ", myCookieStore.getCookies().size() + "" + ", ");
				if(myCookieStore.getCookies().size() > 0){
					Log.e("cookies: ", myCookieStore.getCookies().get(0).getValue());
				}
				callback.getTokenSuccess(content);
			}
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				callback.getTokenFailure();
			}
		});
	}
	public static void getAuthen (Context mContext, final GetAuthenListener callback, String userName, String passWd, String token){
		AsyncHttpClient client = new AsyncHttpClient();
		JSONObject json = new JSONObject();
		addHeader(mContext, client);
		try {
			json.put("passwd", passWd);
			//StringEntity se = new StringEntity("passwd=" + passWd);
			String url = URL.urlAuthen(userName, token);
			Log.e("getAuthen", url);
			userName = Uri.encode(userName);
			String body = "username=" + userName + "&passwd=thangibrahim"+
						"&Submit=Login&option=com_user&task=login" + 
						"&return=aW5kZXgucGhwP29wdGlvbj1jb21fdXNlciZ2aWV3PWxvZ2luJmZvcm1hdD1qc29u=&" + 
						token + "=1&format=json";
			
			StringEntity se = new StringEntity(body);
			/*
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("passwd", passWd));
			nameValuePairs.add(new BasicNameValuePair("username", "thang.ibrahim@gmail.com"));
			nameValuePairs.add(new BasicNameValuePair("Submit", "Login"));
			nameValuePairs.add(new BasicNameValuePair("option", "com_user"));
			nameValuePairs.add(new BasicNameValuePair("return", "aW5kZXgucGhwP29wdGlvbj1jb21fdXNlciZ2aWV3PWxvZ2luJmZvcm1hdD1qc29u"));
			nameValuePairs.add(new BasicNameValuePair(token, "1"));
			nameValuePairs.add(new BasicNameValuePair("format", "json"));
					
			UrlEncodedFormEntity en = new UrlEncodedFormEntity(nameValuePairs);
			*/
			client.post(mContext, URL.urlAuthen(userName, token), se, "application/x-www-form-urlencoded", new AsyncHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						String content) {
					// TODO Auto-generated method stub
					callback.getAuthenSuccess(content);
				}
				@Override
				public void onFailure(Throwable error, String content) {
					// TODO Auto-generated method stub
					if(content!= null)
					Log.e("Error Authen: ", content);
					callback.getAuthenFailure();
				}
			}, json.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			callback.getAuthenFailure();
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			callback.getAuthenFailure();
		}
		
	}
	
	public static void getListLiveTv(Context mContext, String token, final GetListVideoLiveListener callback){
		String keyString = "a2656ca61278d7a0bcc9df878a94a967";
		String signature = HMAC.hmacDigest(token, keyString, "HmacMD5");
		
		AsyncHttpClient client = new AsyncHttpClient();
		addHeader(mContext, client);
		
		Log.e("Url get LiveTv: ", URL.urlGetLiveChannel(signature));
		client.get(mContext, URL.urlGetLiveChannel(signature), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String content) {
				// TODO Auto-generated method stub
				//super.onSuccess(statusCode, headers, content);
				MediaObject media = DecoderJson.getListMedia(content);
				callback.getVideoSuccess(media);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				//super.onFailure(error, content);
				callback.getVideoFailure();
			}
		});
	}
	
	public static void getStreamUrlFromData (Context mContext, String url, final GetStreammingUrl callback){
		AsyncHttpClient client = new AsyncHttpClient();
		client.get(mContext, url, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String content) {
				// TODO Auto-generated method stub
				//super.onSuccess(statusCode, headers, content);
				
				callback.getStreammingUrl(DecoderJson.getStreammingUrlFromXML(content));
			}
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
			}
		});
		/*
		new AsyncTask<String, Void, String>() {

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				XMLParser parser = new XMLParser();
				Log.e("url", params[0]);
				String xml = parser.getXmlFromUrl(params[0]);
				Log.e("data", xml);
				Document doc = parser.getDomElement(xml);
				
				//doc.get
				String returnCode = parser.getAttribute((Element) doc.getDocumentElement(), "code");
				Log.e("returnCode", returnCode);
				if(returnCode.equals("200")){
					NodeList nlData = doc.getElementsByTagName("data");
					for (int i = 0; i < nlData.getLength(); i++) {
						Element e = (Element) nlData.item(i);
						NodeList nlChannel = e.getElementsByTagName("channel");
						String streamUrl = parser.getValue((Element) nlChannel.item(0), "stream_url");
						return streamUrl;
					}
				}
				return "";
			}
			protected void onPostExecute(String result) {
				Log.e("UrlStreamming", result);
			}
			
		}.execute(new String[] {url});
		
		*/
		
	}
}
